<template>
  <div class="coursera-course-detail" v-loading="loading">
    <!-- Coursera风格的头部导航 -->
    <div class="course-nav" v-if="course">
      <div class="nav-container">
        <div class="breadcrumb">
          <button @click="goBack" class="back-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <polyline points="15,18 9,12 15,6"></polyline>
            </svg>
            返回
          </button>
          <span class="breadcrumb-separator">/</span>
          <span class="breadcrumb-current">{{ course.title }}</span>
        </div>
      </div>
    </div>

    <!-- Coursera风格的课程主要内容 -->
    <div class="course-main" v-if="course">
      <div class="main-container">
        <!-- 左侧内容区域 -->
        <div class="course-content-area">
          <!-- 课程头部信息 -->
          <div class="course-header">
            <div class="course-meta-info">
              <div class="category-badge">{{ getCategoryName(course.categoryId) }}</div>
              <h1 class="course-title">{{ course.title }}</h1>
              <p class="course-subtitle">{{ course.description }}</p>
              
              <!-- 课程统计信息 -->
              <div class="course-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ course.enrollmentCount || 12543 }}+</div>
                  <div class="stat-label">已有学员注册</div>
                </div>
                <div class="stat-separator"></div>
                <div class="stat-item">
                  <div class="rating-info">
                    <span class="rating-score">{{ (course.averageRating || 4.6).toFixed(1) }}</span>
                    <div class="rating-stars">
                      <svg v-for="i in 5" :key="i" 
                           :class="['star', { filled: i <= Math.floor(course.averageRating || 4.6) }]" 
                           width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"></polygon>
                      </svg>
                    </div>
                    <span class="rating-count">({{ course.reviewCount || 2156 }} 评价)</span>
                  </div>
                </div>
              </div>

              <!-- 讲师信息 -->
              <div class="instructor-info">
                <div class="instructor-avatar">
                  <img :src="instructorAvatar" :alt="course.teacherName" />
                </div>
                <div class="instructor-details">
                  <div class="instructor-label">授课讲师</div>
                  <div class="instructor-name">{{ course.teacherName || '未知讲师' }}</div>
                  <div class="instructor-title">高级软件工程师</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 课程内容标签页 -->
          <div class="course-content-tabs">
            <div class="tabs-nav">
              <button 
                v-for="tab in courseDetailTabs" 
                :key="tab.key"
                :class="['tab-btn', { active: activeTab === tab.key }]"
                @click="activeTab = tab.key"
              >
                {{ tab.label }}
              </button>
            </div>
            
            <!-- 标签页内容 -->
            <div class="tab-content">
              <!-- 课程概述 -->
              <div v-if="activeTab === 'overview'" class="tab-panel">
                <div class="overview-section">
                  <h3>课程简介</h3>
                  <p class="course-description">{{ course.description }}</p>
                  
                  <h3>学习成果</h3>
                  <ul class="learning-outcomes">
                    <li v-for="outcome in learningOutcomes" :key="outcome">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <polyline points="20,6 9,17 4,12"></polyline>
                      </svg>
                      {{ outcome }}
                    </li>
                  </ul>
                  
                  <h3>课程技能</h3>
                  <div class="skills-tags">
                    <span v-for="skill in courseSkills" :key="skill" class="skill-tag">
                      {{ skill }}
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 课程大纲 -->
              <div v-if="activeTab === 'syllabus'" class="tab-panel">
                <div class="syllabus-section">
                  <h3>课程大纲</h3>
                  <div class="syllabus-info">
                    <span>{{ lessons.length }} 个章节</span>
                    <span>•</span>
                    <span>{{ videoLessonCount }} 个视频</span>
                    <span v-if="documentLessonCount > 0">• {{ documentLessonCount }} 个文档</span>
                    <span>•</span>
                    <span>总计 {{ formatDuration(totalDuration) }}</span>
                  </div>
                  
                  <div class="syllabus-content">
                    <div v-for="(lesson, index) in lessons" :key="lesson.id" class="lesson-item">
                      <div class="lesson-header" @click="toggleLesson(index)">
                        <div class="lesson-info">
                          <svg class="expand-icon" :class="{ expanded: expandedLessons.includes(index) }" 
                               width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <polyline points="6,9 12,15 18,9"></polyline>
                          </svg>
                          <span class="lesson-title">模块 {{ index + 1 }}: {{ lesson.title }}</span>
                        </div>
                        <div class="lesson-meta">
                          <span>{{ getLessonTypeText(lesson.lessonType) }}</span>
                          <span>{{ formatDuration(lesson.duration) }}</span>
                          <span v-if="lesson.isFree" class="free-indicator">免费试看</span>
                        </div>
                      </div>
                      
                      <div v-if="expandedLessons.includes(index)" class="lesson-content">
                        <div class="video-item" @click="playLesson(lesson)">
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <polygon points="5,3 19,12 5,21"></polygon>
                          </svg>
                          <span class="video-title">{{ lesson.title }}</span>
                          <span class="lesson-type-badge">{{ getLessonTypeText(lesson.lessonType) }}</span>
                          <span class="video-duration">{{ formatDuration(lesson.duration) }}</span>
                          <span v-if="lesson.isFree" class="free-badge">免费</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 课程考试 -->
              <div v-if="activeTab === 'exams'" class="tab-panel">
                <div class="exams-section">
                  <h3>课程考试</h3>
                  <div class="section-meta">
                    <span>{{ exams.length }} 个考试</span>
                  </div>
                  
                  <div v-if="!backendConnected" class="backend-error">
                    <div class="error-icon">⚠️</div>
                    <h4>后端服务连接失败</h4>
                    <p>无法加载考试信息，请检查后端服务是否正常运行</p>
                    <button @click="retryLoadExams" class="retry-btn">重试</button>
                  </div>
                  
                  <div v-else-if="exams.length === 0" class="empty-exams">
                    <div class="empty-icon">📝</div>
                    <h4>暂无课程考试</h4>
                    <p>本课程暂未设置考试</p>
                  </div>
                  
                  <div v-else class="exams-list">
                    <div 
                      v-for="exam in exams" 
                      :key="exam.id" 
                      class="exam-item"
                    >
                      <div class="exam-header">
                        <div class="exam-info">
                          <h4 class="exam-title">{{ exam.title }}</h4>
                          <p class="exam-description">{{ exam.description }}</p>
                          <div class="exam-meta">
                            <span class="exam-duration">时长: {{ exam.timeLimit || 60 }} 分钟</span>
                            <span class="exam-questions">题目: {{ exam.questionCount || 0 }} 题</span>
                            <span class="exam-pass-score">及格分: {{ exam.passScore || 60 }} 分</span>
                          </div>
                        </div>
                        <div class="exam-actions">
                          <a 
                            v-if="isEnrolled"
                            @click.prevent="startExam(exam)"
                            class="start-exam-btn"
                            role="button"
                          >
                            开始考试
                          </a>
                          <button v-else class="disabled-btn" disabled>
                            需要报名后参加
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 问答社区 -->
              <div v-if="activeTab === 'community'" class="tab-panel">
                <div class="community-section">
                  <h3>课程问答与讨论</h3>
                  <p class="community-description">在问答区提出问题、查看讨论与笔记，和同学一起交流学习。(courseId: {{ courseId }})</p>
                  
                  <div class="community-features">
                    <div class="feature-item">
                      <div class="feature-icon">❓</div>
                      <div class="feature-content">
                        <h4>提问答疑</h4>
                        <p>遇到问题可以在这里提问，讲师和同学会帮助解答</p>
                      </div>
                    </div>
                    <div class="feature-item">
                      <div class="feature-icon">💡</div>
                      <div class="feature-content">
                        <h4>学习笔记</h4>
                        <p>分享学习心得和笔记，与其他学员交流经验</p>
                      </div>
                    </div>
                    <div class="feature-item">
                      <div class="feature-icon">🎓</div>
                      <div class="feature-content">
                        <h4>AI学习助手</h4>
                        <p>智能AI助手24小时在线，随时解答学习疑问</p>
                      </div>
                    </div>
                  </div>
                  
                  <div class="community-actions">
                    <button class="cta-btn primary" @click="goToCommunity">
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                      </svg>
                      进入问答社区
                    </button>
                  </div>
                </div>
              </div>
              
              <!-- 评价 -->
              <div v-if="activeTab === 'reviews'" class="tab-panel">
                <div class="reviews-section">
                  <h3>学员评价</h3>
                  <div class="reviews-summary">
                    <div class="rating-overview">
                      <div class="overall-rating">
                        <span class="rating-number">{{ (course.averageRating || 4.6).toFixed(1) }}</span>
                        <div class="rating-stars">
                          <svg v-for="i in 5" :key="i" 
                               :class="['star', { filled: i <= Math.floor(course.averageRating || 4.6) }]" 
                               width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"></polygon>
                          </svg>
                        </div>
                        <span class="reviews-count">基于 {{ course.reviewCount || 2156 }} 条评价</span>
                      </div>
                    </div>
                  </div>
                  
                  <div class="reviews-list">
                    <div v-for="review in mockReviews" :key="review.id" class="review-item">
                      <div class="review-header">
                        <div class="reviewer-info">
                          <img :src="review.avatar" :alt="review.name" class="reviewer-avatar" />
                          <div class="reviewer-details">
                            <div class="reviewer-name">{{ review.name }}</div>
                            <div class="review-date">{{ review.date }}</div>
                          </div>
                        </div>
                        <div class="review-rating">
                          <svg v-for="i in 5" :key="i" 
                               :class="['star', { filled: i <= review.rating }]" 
                               width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                            <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"></polygon>
                          </svg>
                        </div>
                      </div>
                      <p class="review-content">{{ review.content }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 - Coursera风格 -->
        <div class="course-sidebar">
          <!-- 课程预览卡片 -->
          <div class="course-preview-card">
            <div class="preview-image">
              <img :src="coverUrl" :alt="course.title" @error="onCoverError" />
              <button class="play-preview" @click="playPreview">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <polygon points="5,3 19,12 5,21"></polygon>
                </svg>
                预览课程
              </button>
            </div>
            
            <div class="card-content">
              <!-- 公益平台信息 -->
              <div class="price-section">
                <div class="free-course">
                  <div class="free-badge">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                    </svg>
                    公益免费学习
                  </div>
                  <p class="platform-description">致力于为所有人提供高质量的免费教育资源</p>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="action-buttons">
                <button 
                  v-if="!isEnrolled" 
                  @click="handleEnroll" 
                  class="primary-btn enroll-btn"
                  :disabled="enrollLoading"
                >
                  <span class="modern-icon">👤</span>
                  <span v-if="enrollLoading">选课中...</span>
                  <span v-else>免费选课</span>
                </button>
                
                <button 
                  v-else 
                  @click="handleUnenroll" 
                  class="secondary-btn unenroll-btn"
                  :disabled="enrollLoading"
                >
                  <span class="modern-icon">❌</span>
                  <span v-if="enrollLoading">退选中...</span>
                  <span v-else>退选课程</span>
                </button>
                
                <button 
                  v-if="isEnrolled" 
                  @click="continueStudy" 
                  class="primary-btn continue-btn"
                >
                  <span class="modern-icon">▶️</span>
                  继续学习
                </button>
                
                <button @click="toggleFavorite" class="secondary-btn favorite-btn" :class="{ active: isFavorited }">
                  <span class="modern-icon">{{ isFavorited ? '❤️' : '🤍' }}</span>
                  {{ isFavorited ? '已收藏' : '收藏课程' }}
                </button>
                
                <button @click="shareCourse" class="secondary-btn share-btn">
                  <span class="modern-icon">🔗</span>
                  分享课程
                </button>
              </div>
              
              <!-- 课程包含内容 -->
              <div class="course-includes">
                <h4>此课程包含：</h4>
                <ul class="includes-list">
                  <li>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <polygon points="23,7 16,12 23,17"></polygon>
                      <rect x="1" y="5" width="15" height="14" rx="2" ry="2"></rect>
                    </svg>
                    {{ formatDuration((course as any).duration || 120) }} 视频内容
                  </li>
                  <li>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                      <polyline points="14,2 14,8 20,8"></polyline>
                      <line x1="16" y1="13" x2="8" y2="13"></line>
                      <line x1="16" y1="17" x2="8" y2="17"></line>
                      <polyline points="10,9 9,9 8,9"></polyline>
                    </svg>
                    资源下载
                  </li>
                  <li>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path>
                    </svg>
                    结业证书
                  </li>
                  <li>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                    </svg>
                    讲师答疑
                  </li>
                  <li>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                      <circle cx="12" cy="12" r="10"></circle>
                      <polyline points="12,6 12,12 16,14"></polyline>
                    </svg>
                    终身访问
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- AI助手组件 -->
    <AIAssistant 
      v-if="authStore.user" 
      :userId="authStore.user.id" 
      :courseId="course ? courseId : undefined" 
    />
    
    <!-- 未登录用户的AI助手 -->
    <div v-else class="ai-assistant-login-prompt">
      <div class="ai-prompt-card">
        <div class="ai-prompt-icon">🤖</div>
        <h3>AI学习助手</h3>
        <p>登录后即可使用智能AI助手，获得个性化学习指导和知识库支持</p>
        <button @click="router.push('/login')" class="login-prompt-btn">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
            <polyline points="10,17 15,12 10,7"></polyline>
            <line x1="15" y1="12" x2="3" y2="12"></line>
          </svg>
          立即登录使用AI助手
        </button>
      </div>
    </div>·
    
    <!-- 加载失败提示 -->
    <div v-if="!loading && !course" class="error-state">
      <div class="error-icon">😕</div>
      <h2>课程加载失败</h2>
      <p>课程ID: {{ courseId }}</p>
      <button @click="loadCourseDetail" class="retry-btn">重新加载</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { courseApi, enrollmentApi, type Course, type Lesson } from '@/api/course'
import { examApi, type Exam } from '@/api/exam'
import { ElMessage, ElMessageBox } from 'element-plus'
import AIAssistant from '@/components/AIAssistant.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const courseId = Number(route.params.id)

// 状态管理
const course = ref<Course | null>(null)
const lessons = ref<Lesson[]>([])
const exams = ref<Exam[]>([])
const loading = ref(false)
const enrollLoading = ref(false)
const isEnrolled = ref(false)
const activeTab = ref('overview')
const backendConnected = ref(true)

// Coursera风格的新状态
const expandedLessons = ref<number[]>([])
const isFavorited = ref(false)
const courseDetailTabs = ref([
  { key: 'overview', label: '课程概述' },
  { key: 'syllabus', label: '课程大纲' },
  { key: 'exams', label: '课程考试' },
  { key: 'community', label: '问答社区' },
  { key: 'reviews', label: '学员评价' }
])

// 模拟数据
const instructorAvatar = ref('/default-avatar.png')
const learningOutcomes = ref([
  '掌握编程基础概念和语法',
  '能够独立开发小型项目',
  '理解面向对象编程思想',
  '具备调试和问题解决能力',
  '为进阶学习打下坚实基础'
])

const courseSkills = ref([
  'JavaScript', 'HTML/CSS', 'React', 'Node.js', 'Git', '数据结构', '算法基础'
])

const mockVideos = ref([
  { id: 1, title: '课程介绍', duration: 15 },
  { id: 2, title: '环境搭建', duration: 20 },
  { id: 3, title: '基础语法', duration: 30 },
  { id: 4, title: '实践练习', duration: 25 },
  { id: 5, title: '总结与回顾', duration: 10 }
])

const mockReviews = ref([
  {
    id: 1,
    name: '李明',
    avatar: '/default-avatar.png',
    rating: 5,
    date: '2024年1月15日',
    content: '课程内容很棒，讲师讲解清晰，项目实战很有帮助。强烈推荐给想学编程的朋友！'
  },
  {
    id: 2,
    name: '张小芳',
    avatar: '/default-avatar.png',
    rating: 4,
    date: '2024年1月10日',
    content: '总体来说是个不错的课程，内容丰富，只是有些地方讲得稍微快了点。'
  },
  {
    id: 3,
    name: '王大明',
    avatar: '/default-avatar.png',
    rating: 5,
    date: '2024年1月8日',
    content: '从零基础到入门，这个课程帮了我很大忙。现在已经能够独立做一些小项目了。'
  }
])

// 是否存在登录令牌（避免在模板直接访问 localStorage 引发警告）
const tokenExists = computed(() => {
  try {
    return typeof window !== 'undefined' && !!window.localStorage?.getItem('access_token')
  } catch {
    return false
  }
})

// 分类
const categories = ref<any[]>([
  { id: 1, name: 'Web开发' },
  { id: 2, name: '移动开发' },
  { id: 3, name: '数据科学' },
  { id: 4, name: '人工智能' },
  { id: 5, name: '云计算' }
])

// 默认封面图片
const defaultCovers = [
  'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=240&fit=crop',
  'https://images.unsplash.com/photo-1517077304055-6e89abbf09b0?w=400&h=240&fit=crop',
  'https://images.unsplash.com/photo-1515879218367-8466d910aaa4?w=400&h=240&fit=crop',
  'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=400&h=240&fit=crop'
]

// 计算属性
const tabs = computed(() => [
  { id: 'overview', label: '概述', icon: '📖', count: null },
  { id: 'lessons', label: '章节', icon: '📚', count: lessons.value.length },
  { id: 'exams', label: '考试', icon: '📝', count: exams.value.length },
  { id: 'community', label: '问答', icon: '💬', count: null }
])

// 课程加载
const loadCourseDetail = async () => {
  try {
    loading.value = true
    console.log('📚 开始加载课程详情，courseId:', courseId)
    
    // 并行加载课程信息、章节和考试
    const [courseResponse, lessonsResponse] = await Promise.all([
      courseApi.getCourseDetail(courseId),
      courseApi.getCourseLessons(courseId)
    ])
    
    course.value = courseResponse
    lessons.value = lessonsResponse || []
    
    console.log('✅ 课程详情加载成功:', course.value)
    console.log('✅ 课程章节加载成功:', lessons.value.length, '个章节')
    
    // 加载考试信息（可能失败，不影响主要功能）
    await loadExams()
    
    // 检查报名状态
    await checkEnrollmentStatus()
    
  } catch (error) {
    console.error('❌ 课程详情加载失败:', error)
    ElMessage.error('课程加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const loadExams = async () => {
  try {
    console.log('📝 开始加载考试信息...')
    const examResponse = await examApi.getByCourse(courseId)
    exams.value = (examResponse as any)?.content || examResponse || []
    console.log('✅ 考试信息加载成功:', exams.value.length, '个考试')
    backendConnected.value = true
  } catch (error) {
    console.error('❌ 考试加载失败，可能是后端服务未启动:', error)
    exams.value = []
    backendConnected.value = false
  }
}

const checkEnrollmentStatus = async () => {
  if (!authStore.isLoggedIn) {
    isEnrolled.value = false
    return
  }

  const storageKey = `course_${courseId}_enrolled`
  const saved = localStorage.getItem(storageKey)
  const localEnrolled = saved === 'true'

  // 先用本地状态回显，避免闪烁
  if (saved !== null) {
    isEnrolled.value = localEnrolled
    console.log('🔄 从本地存储恢复状态:', isEnrolled.value ? '已报名' : '未报名')
  }

  // 优先使用精确状态接口（若存在）
  try {
    const precise = await enrollmentApi.checkEnrollmentStatus(courseId)
    if (typeof precise === 'boolean') {
      isEnrolled.value = precise
      localStorage.setItem(storageKey, precise.toString())
      console.log('✅ 精确状态接口结果:', precise ? '已报名' : '未报名')
      return
    }
  } catch (_) {
    // 忽略，继续回退逻辑
  }

  // 回退：我的选课列表。注意：若本地为 true，不因回退失败而强制改为 false
  try {
    const enrollments = await enrollmentApi.getMyEnrollments()
    let list: any[] = []
    if (Array.isArray(enrollments)) list = enrollments
    else if (enrollments?.content) list = enrollments.content
    else if (enrollments?.data) list = enrollments.data

    const found = list.some((e: any) => {
      const cid = Number(courseId)
      return Number(e?.courseId) === cid || Number(e?.course_id) === cid || Number(e?.course?.id) === cid
    })

    // 仅在明确找到时置为 true；若未找到且本地是 true，则保持 true
    if (found || !localEnrolled) {
      isEnrolled.value = found
      localStorage.setItem(storageKey, found.toString())
    }

    console.log('✅ 回退状态检查:', isEnrolled.value ? '已报名' : '未报名')
  } catch (error) {
    console.warn('⚠️ 回退状态检查失败，保留本地状态:', error)
  }
}

// 报名操作
const handleEnroll = async () => {
  if (!authStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    enrollLoading.value = true
    await enrollmentApi.enrollCourse(courseId)
    isEnrolled.value = true
    
    // 立即保存到本地存储
    const storageKey = `course_${courseId}_enrolled`
    localStorage.setItem(storageKey, 'true')
    
    ElMessage.success('选课成功！')
    console.log('✅ 选课成功，状态已保存')
  } catch (error: any) {
    console.error('选课失败:', error)
    const errorMsg = error.message || error.response?.data?.message || ''
    if (error.response?.status === 409 || 
        errorMsg.includes('已经选择') || 
        errorMsg.includes('已经选过') ||
        errorMsg.includes('already enrolled')) {
      ElMessage.info('您已经选择了这门课程')
      isEnrolled.value = true
      // 保存已选课状态
      const storageKey = `course_${courseId}_enrolled`
      localStorage.setItem(storageKey, 'true')
    } else {
      ElMessage.error('选课失败，请稍后重试')
    }
  } finally {
    enrollLoading.value = false
  }
}

const handleUnenroll = async () => {
  try {
    await ElMessageBox.confirm('确定要退选这门课程吗？', '确认退选', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    enrollLoading.value = true
    await enrollmentApi.unenrollCourse(courseId)
    isEnrolled.value = false
    
    // 立即更新本地存储
    const storageKey = `course_${courseId}_enrolled`
    localStorage.setItem(storageKey, 'false')
    
    ElMessage.success('退选成功')
    console.log('✅ 退选成功，状态已更新')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('退选失败:', error)
      ElMessage.error('退选失败，请稍后重试')
    }
  } finally {
    enrollLoading.value = false
  }
}

const continueStudy = () => {
  if (lessons.value.length > 0) {
    const firstLesson = lessons.value[0]
    if (firstLesson.lessonType === 'VIDEO' && firstLesson.videoUrl) {
      router.push(`/player/video?url=${encodeURIComponent(firstLesson.videoUrl)}&title=${encodeURIComponent(firstLesson.title)}`)
    } else if (firstLesson.lessonType === 'DOCUMENT' && firstLesson.contentUrl) {
      router.push(`/player/document?url=${encodeURIComponent(firstLesson.contentUrl)}&title=${encodeURIComponent(firstLesson.title)}`)
    } else {
      ElMessage.info('课程内容正在准备中')
    }
  } else {
    ElMessage.info('暂无课程内容')
  }
}

// 章节播放
const playLesson = (lesson: Lesson) => {
  if (!isEnrolled.value && !lesson.isFree) {
    ElMessage.warning('请先报名课程')
    return
  }

  if (lesson.lessonType === 'VIDEO' && lesson.videoUrl) {
    router.push(`/player/video?url=${encodeURIComponent(lesson.videoUrl)}&title=${encodeURIComponent(lesson.title)}`)
  } else if (lesson.lessonType === 'DOCUMENT' && lesson.contentUrl) {
    router.push(`/player/document?url=${encodeURIComponent(lesson.contentUrl)}&title=${encodeURIComponent(lesson.title)}`)
  } else {
    ElMessage.info('该章节内容暂不可用')
  }
}

// 考试相关
const startExam = (exam: any) => {
  if (!exam || !exam.id) {
    ElMessage.error('考试信息有误，请重试')
    return
  }
  
  if (!isEnrolled.value) {
    ElMessage.warning('请先选课后参加考试')
    return
  }
  
  console.log('🎯 开始考试:', exam)
  // 跳转到考试页面
  router.push(`/exam/${exam.id}`)
}

// 导航
const goBack = () => {
  router.push('/courses')
}

const goToCommunity = () => {
  console.log('🏛️ 进入问答社区, courseId:', courseId)
  const targetPath = `/courses/${courseId}/qna`
  console.log('🎯 跳转路径:', targetPath)
  
  try {
    router.push(targetPath)
    console.log('✅ 路由跳转成功')
  } catch (error) {
    console.error('❌ 路由跳转失败:', error)
    ElMessage.error('页面跳转失败，请重试')
  }
}

const retryLoadExams = async () => {
  console.log('🔄 重新尝试加载考试...')
  backendConnected.value = true // 重置连接状态
  await loadExams()
}

// 工具方法
const getDefaultCover = () => {
  return defaultCovers[courseId % defaultCovers.length]
}

const resolveCover = (url?: string) => {
  if (!url) return getDefaultCover()
  if (url.startsWith('/uploads/')) return `http://localhost:8080${url}`
  return url
}

const coverUrl = ref<string>(getDefaultCover())

const onCoverError = () => {
  coverUrl.value = getDefaultCover()
}

const getCategoryName = (categoryId?: number) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category?.name || '未分类'
}

const getDifficultyText = (difficulty?: string) => {
  const texts = {
    BEGINNER: '初级',
    INTERMEDIATE: '中级', 
    ADVANCED: '高级',
    EXPERT: '专家级',
    EASY: '简单',
    MEDIUM: '中等',
    HARD: '困难'
  }
  return texts[difficulty as keyof typeof texts] || '中级'
}

const getLessonTypeText = (type?: string) => {
  const texts = {
    VIDEO: '视频',
    DOCUMENT: '文档',
    QUIZ: '测验',
    ASSIGNMENT: '作业'
  }
  return texts[type as keyof typeof texts] || '内容'
}

const formatDuration = (duration?: number) => {
  if (!duration) return '未知'
  if (duration < 60) return `${duration}分钟`
  const hours = Math.floor(duration / 60)
  const minutes = duration % 60
  return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
}

const formatDate = (dateStr?: string) => {
  if (!dateStr) return '未知'
  try {
    return new Date(dateStr).toLocaleDateString('zh-CN')
  } catch {
    return '未知'
  }
}

// 新增方法
const toggleLesson = (index: number) => {
  if (expandedLessons.value.includes(index)) {
    expandedLessons.value = expandedLessons.value.filter(i => i !== index)
  } else {
    expandedLessons.value.push(index)
  }
}

const toggleFavorite = () => {
  isFavorited.value = !isFavorited.value
  ElMessage.success(isFavorited.value ? '已添加到收藏夹' : '已从收藏夹移除')
}

const playPreview = () => {
  ElMessage.info('课程预览功能即将推出')
}

const shareCourse = () => {
  if (navigator.share) {
    navigator.share({
      title: course.value?.title,
      text: `推荐一门优质的免费课程：${course.value?.title}`,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      ElMessage.success('课程链接已复制到剪贴板')
    }).catch(() => {
      ElMessage.info('请手动复制当前页面链接分享给朋友')
    })
  }
}

// 计算真实的课程统计数据
const videoLessonCount = computed(() => {
  return lessons.value.filter(lesson => lesson.lessonType === 'VIDEO').length
})

const documentLessonCount = computed(() => {
  return lessons.value.filter(lesson => lesson.lessonType === 'DOCUMENT').length
})

const totalDuration = computed(() => {
  return lessons.value.reduce((total, lesson) => total + (lesson.duration || 0), 0)
})

// 生命周期
onMounted(() => {
  console.log('🚀 课程详情页面初始化, courseId:', courseId)
  loadCourseDetail()
})
</script>

<style scoped>
/* CSS变量定义 */
:root {
  --coursera-blue: #0056d3;
  --coursera-blue-dark: #003b94;
  --coursera-blue-light: #e6f0ff;
  --coursera-orange: #ff9900;
  --coursera-gray: #f7f9fc;
  --text-primary: #1a1a1a;
  --text-secondary: #666666;
  --border-color: #e5e7eb;
  --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
  --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* Coursera风格的课程详情页面 */

.coursera-course-detail {
  min-height: 100vh;
  background: #ffffff;
}

/* 课程导航栏 */
.course-nav {
  background: white;
  border-bottom: 1px solid var(--border-color);
  padding: 16px 0;
  position: sticky;
  top: 64px;
  z-index: 100;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: var(--coursera-blue);
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background: var(--coursera-blue-light);
}

.breadcrumb-separator {
  color: var(--text-secondary);
}

.breadcrumb-current {
  color: var(--text-secondary);
  font-weight: 500;
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 主要内容区域 */
.course-main {
  background: var(--coursera-gray);
  min-height: calc(100vh - 120px);
}

.main-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px 24px;
  display: grid;
  grid-template-columns: 1fr 360px;
  gap: 32px;
  align-items: start;
}

/* 左侧内容区域 */
.course-content-area {
  background: white;
  border-radius: 8px;
  box-shadow: var(--shadow-sm);
  overflow: hidden;
}

.course-header {
  padding: 32px;
  border-bottom: 1px solid var(--border-color);
}

.category-badge {
  display: inline-block;
  background: var(--coursera-blue-light);
  color: var(--coursera-blue);
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 16px;
}

.course-title {
  font-size: 32px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1.3;
  margin-bottom: 16px;
}

.course-subtitle {
  font-size: 18px;
  color: var(--text-secondary);
  line-height: 1.5;
  margin-bottom: 24px;
}

.course-stats {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 32px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-top: 4px;
}

.stat-separator {
  width: 1px;
  height: 32px;
  background: var(--border-color);
}

.rating-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-score {
  font-size: 18px;
  font-weight: 700;
  color: var(--coursera-orange);
}

.rating-stars {
  display: flex;
  gap: 2px;
}

.star {
  color: #e9ecef;
  transition: color 0.2s;
}

.star.filled {
  color: var(--coursera-orange);
}

.rating-count {
  font-size: 14px;
  color: var(--text-secondary);
}

.instructor-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.instructor-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
}

.instructor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.instructor-details {
  flex: 1;
}

.instructor-label {
  font-size: 12px;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 4px;
}

.instructor-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 2px;
}

.instructor-title {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 课程内容标签页 */
.course-content-tabs {
  padding: 32px;
}

.tabs-nav {
  display: flex;
  gap: 2px;
  margin-bottom: 32px;
  background: #f8f9fa;
  padding: 4px;
  border-radius: 8px;
}

.tab-btn {
  flex: 1;
  padding: 12px 16px;
  background: transparent;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
  color: var(--text-secondary);
}

.tab-btn.active {
  background: white;
  color: var(--coursera-blue);
  box-shadow: var(--shadow-sm);
}

.tab-btn:hover:not(.active) {
  color: var(--coursera-blue);
  background: rgba(0, 86, 211, 0.05);
}

.tab-content {
  min-height: 400px;
}

.tab-panel {
  animation: fadeIn 0.3s ease-in-out;
}

/* 概述部分 */
.overview-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 16px;
  margin-top: 32px;
}

.overview-section h3:first-child {
  margin-top: 0;
}

.course-description {
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 16px;
}

.learning-outcomes {
  list-style: none;
  padding: 0;
  margin: 0 0 16px 0;
}

.learning-outcomes li {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
  color: var(--text-primary);
}

.learning-outcomes svg {
  color: #22c55e;
  flex-shrink: 0;
  margin-top: 2px;
}

.skills-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.skill-tag {
  background: var(--coursera-blue-light);
  color: var(--coursera-blue);
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

/* 大纲部分 */
.syllabus-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

.lesson-item {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  margin-bottom: 8px;
  overflow: hidden;
}

.lesson-header {
  padding: 16px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  transition: background-color 0.2s;
}

.lesson-header:hover {
  background: #f8f9fa;
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.expand-icon {
  color: var(--text-secondary);
  transition: transform 0.2s;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.lesson-title {
  font-weight: 500;
  color: var(--text-primary);
}

.lesson-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: var(--text-secondary);
}

.lesson-content {
  background: #f8f9fa;
  padding: 16px;
  border-top: 1px solid var(--border-color);
}

.video-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  font-size: 14px;
  color: var(--text-secondary);
}

.video-item svg {
  color: var(--coursera-blue);
}

.video-title {
  flex: 1;
  color: var(--text-primary);
}

.video-duration {
  color: var(--text-secondary);
}

.lesson-type-badge {
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.free-badge {
  background: #e8f5e8;
  color: #2e7d32;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.free-indicator {
  color: #2e7d32;
  font-size: 12px;
  font-weight: 500;
}

.video-item {
  cursor: pointer;
  transition: background-color 0.2s;
}

.video-item:hover {
  background-color: #f5f5f5;
}

/* 评价部分 */
.reviews-summary {
  margin-bottom: 32px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
}

.overall-rating {
  display: flex;
  align-items: center;
  gap: 16px;
}

.rating-number {
  font-size: 48px;
  font-weight: 700;
  color: var(--coursera-orange);
}

.reviews-count {
  font-size: 14px;
  color: var(--text-secondary);
}

.review-item {
  border-bottom: 1px solid var(--border-color);
  padding: 24px 0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reviewer-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.reviewer-name {
  font-weight: 500;
  color: var(--text-primary);
}

.review-date {
  font-size: 12px;
  color: var(--text-secondary);
}

.review-rating {
  display: flex;
  gap: 2px;
}

.review-content {
  color: var(--text-secondary);
  line-height: 1.6;
  margin: 0;
}

/* 考试部分样式 */
.exams-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 16px;
}

.section-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

.backend-error, .empty-exams {
  text-align: center;
  padding: 40px 20px;
}

.error-icon, .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.backend-error h4, .empty-exams h4 {
  color: var(--text-primary);
  margin-bottom: 8px;
}

.backend-error p, .empty-exams p {
  color: var(--text-secondary);
  margin-bottom: 24px;
}

.exam-item {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  transition: box-shadow 0.2s;
}

.exam-item:hover {
  box-shadow: var(--shadow-md);
}

.exam-header {
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
}

.exam-info {
  flex: 1;
}

.exam-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.exam-description {
  color: var(--text-secondary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.exam-meta {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: var(--text-secondary);
}

.exam-actions {
  flex-shrink: 0;
}

.start-exam-btn, .disabled-btn {
  padding: 12px 24px;
  border-radius: 6px;
  font-weight: 600;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

/* 强化“开始考试”可见性，适配 a 或 button */

.start-exam-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 136px;
  min-height: 40px;
  padding: 12px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8) !important; /* 强制蓝色背景 */
  color: #ffffff !important; /* 白色文字 */
  text-decoration: none !important;
  font-size: 16px;
  font-weight: 700;
  line-height: 1;
  border: none;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.35);
  text-align: center;
  cursor: pointer;
  position: relative;
  z-index: 2; /* 避免被同层元素遮挡 */
}

.start-exam-btn:hover {
  background: var(--coursera-blue-dark);
}

.disabled-btn {
  background: #f8f9fa;
  color: var(--text-secondary);
  cursor: not-allowed;
}

.cta-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 16px 32px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.cta-btn.primary {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
}

.cta-btn.primary:hover {
  background: linear-gradient(135deg, #1d4ed8, #1e40af);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

/* 问答社区部分样式 */
.community-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 16px;
}

.community-description {
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 32px;
  font-size: 16px;
}

.community-features {
  display: grid;
  gap: 24px;
  margin-bottom: 32px;
}

.feature-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: transform 0.2s;
}

.feature-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-sm);
}

.feature-icon {
  font-size: 32px;
  flex-shrink: 0;
}

.feature-content h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.feature-content p {
  color: var(--text-secondary);
  line-height: 1.5;
  margin: 0;
}

.community-actions {
  text-align: center;
}

.cta-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 16px 32px;
  background: var(--coursera-blue);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.cta-btn:hover {
  background: var(--coursera-blue-dark);
  transform: translateY(-2px);
}

/* 公益平台样式 */
.free-course {
  text-align: center;
  padding: 16px;
}

.free-badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
  padding: 12px 20px;
  border-radius: 25px;
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 12px;
}

.free-badge svg {
  color: white;
}

.platform-description {
  color: var(--text-secondary);
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

/* 按钮图标样式 */
.primary-btn, .secondary-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.enroll-btn {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border: none;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.enroll-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #1d4ed8, #1e40af);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
}

.continue-btn {
  background: linear-gradient(135deg, #10b981, #059669);
  border: none;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.continue-btn:hover {
  background: linear-gradient(135deg, #059669, #047857);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
}

.favorite-btn {
  border: 2px solid #e5e7eb;
  background: white;
  color: #6b7280;
}

.favorite-btn svg {
  stroke: #6b7280;
}

.favorite-btn:hover {
  border-color: #ef4444;
  color: #ef4444;
  background: #fef2f2;
}

.favorite-btn:hover svg {
  stroke: #ef4444;
}

.favorite-btn.active {
  border-color: #ef4444;
  background: #ef4444;
  color: white;
}

.favorite-btn.active svg {
  stroke: white;
}

.share-btn {
  border: 2px solid #e5e7eb;
  background: white;
  color: #6b7280;
}

.share-btn svg {
  stroke: #6b7280;
}

.share-btn:hover {
  border-color: var(--coursera-blue);
  color: var(--coursera-blue);
  background: #eff6ff;
}

.share-btn:hover svg {
  stroke: var(--coursera-blue);
}

/* 现代化图标样式 */
.modern-icon {
  display: inline-block;
  font-size: 16px;
  line-height: 1;
  margin-right: 6px;
}

/* AI助手登录提示 */
.ai-assistant-login-prompt {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 1000;
  max-width: 320px;
}

.ai-prompt-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  padding: 24px;
  text-align: center;
  border: 1px solid #e5e7eb;
}

.ai-prompt-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.ai-prompt-card h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.ai-prompt-card p {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.5;
  margin-bottom: 20px;
}

.login-prompt-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: linear-gradient(135deg, var(--coursera-blue), var(--coursera-blue-dark));
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-prompt-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 86, 211, 0.3);
}

/* 右侧边栏 */
.course-sidebar {
  position: sticky;
  top: 120px;
}

.course-preview-card {
  background: white;
  border-radius: 8px;
  box-shadow: var(--shadow-md);
  overflow: hidden;
}

.preview-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-preview {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.play-preview:hover {
  background: rgba(0, 0, 0, 0.8);
  transform: translate(-50%, -50%) scale(1.1);
}

.card-content {
  padding: 24px;
}

.price-section {
  margin-bottom: 24px;
}

.current-price {
  font-size: 32px;
  font-weight: 700;
  color: var(--text-primary);
}

.current-price.free {
  color: #22c55e;
}

.original-price {
  font-size: 18px;
  color: var(--text-secondary);
  text-decoration: line-through;
  margin-left: 8px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 32px;
}

.primary-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.primary-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #1d4ed8, #1e40af);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

.primary-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.secondary-btn {
  width: 100%;
  padding: 16px;
  background: transparent;
  color: var(--coursera-blue);
  border: 2px solid var(--coursera-blue);
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.secondary-btn:hover {
  background: var(--coursera-blue);
  color: white;
}

.secondary-btn.active {
  background: var(--coursera-blue);
  color: white;
}

.unenroll-btn {
  background: transparent;
  color: #dc3545;
  border: 2px solid #dc3545;
}

.unenroll-btn:hover:not(:disabled) {
  background: #dc3545;
  color: white;
}

.unenroll-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.course-includes h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 16px;
}

.includes-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.includes-list li {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.includes-list svg {
  color: var(--coursera-blue);
  flex-shrink: 0;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 80px 20px;
}

.error-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.error-state h2 {
  color: var(--text-primary);
  margin-bottom: 8px;
}

.error-state p {
  color: var(--text-secondary);
  margin-bottom: 24px;
}

.retry-btn {
  background: var(--coursera-blue);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background: var(--coursera-blue-dark);
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .course-sidebar {
    position: static;
  }
}

@media (max-width: 768px) {
  .nav-container,
  .main-container {
    padding: 16px;
  }
  
  .course-header,
  .course-content-tabs {
    padding: 24px 16px;
  }
  
  .course-title {
    font-size: 24px;
  }
  
  .course-stats {
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .instructor-info {
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
  }
  
  .tabs-nav {
    flex-direction: column;
  }
  
  .overall-rating {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
}
</style>